UIEquipmentAllocation = {}
HelperFunc.SetUIEnv(UIEquipmentAllocation)
local this = UIEquipmentAllocation
this.linkColor = "#" .. G.dataTable["t_global"][tostring(185)]["f_string_value"]

function UIEquipmentAllocation.Init(data, closeFunc)--todo 应该小写 暂时先大写
    local _name, _package = getUIName(PanelNames.UIEquipmentAllocation)
    panelMgr:ShowUI(_name, _package, this.onCreate, Config.useLocalUI)
end

function UIEquipmentAllocation.onCreate(obj)
    -- this.gameObject = obj 
    if not this.hasInit then
        this.hasInit = true
        this.bgClose = obj:GetChild("bgClose")
        this.SmartHeroList = obj:GetChild("list")
        this.smart_list_y = this.SmartHeroList.y 
        this.smart_list_height = this.SmartHeroList.viewHeight
        this.SmartHeroList.itemRenderer = this.UpdateItemRender
        this.btnBack = obj:GetChild("btnBack")
        this.btnAllocation = obj:GetChild("btnAllocation")
        this.addEvent()
    end 

    this.initData()
end


function UIEquipmentAllocation.initData()
    -- this.curHeroPriority = this.GetCurHeroPriority()
    this.curHeroPriority = {}
    this.curHeroPriority[1] = {}
    this.curHeroPriority[2] = {}
    this.curHeroPriority[3] = {}
    equipHandler.sendReqGetSmartWearPriority()
    this.SmartHeroList.numItems = 3
end

function UIEquipmentAllocation.GetCurHeroPriority()
    local hero_priority_data = {}
    hero_priority_data[1] = {}
    hero_priority_data[2] = {}
    hero_priority_data[3] = {}

    local tempOwnerOccupation1 = logicMgr.HeroManager.getOwnerHeroListLevelUp(false, 1, 1)
    local tempOwnerOccupation2 = logicMgr.HeroManager.getOwnerHeroListLevelUp(false, 2, 1)
    local tempOwnerOccupation3 = logicMgr.HeroManager.getOwnerHeroListLevelUp(false, 3, 1)
    local tempOwnerOccupation4 = logicMgr.HeroManager.getOwnerHeroListLevelUp(false, 4, 1)
    local tempOwnerOccupation5 = logicMgr.HeroManager.getOwnerHeroListLevelUp(false, 5, 1)
    local tempOwnerOccupation6 = logicMgr.HeroManager.getOwnerHeroListLevelUp(false, 6, 1)
    local function sort_level( a, b )
        a["level2"] = logicMgr.HeroManager.getHeroShowLevelByPartnerId(a.partnerId) or 0
        b["level2"] = logicMgr.HeroManager.getHeroShowLevelByPartnerId(b.partnerId) or 0
        if a["level2"] > b["level2"] then
            return true
        else
            return false
        end
    end
    table.sort(tempOwnerOccupation1, sort_level)
    table.sort(tempOwnerOccupation2, sort_level)
    table.sort(tempOwnerOccupation3, sort_level)
    table.sort(tempOwnerOccupation4, sort_level)
    table.sort(tempOwnerOccupation5, sort_level)
    table.sort(tempOwnerOccupation6, sort_level) 
    if tempOwnerOccupation1[1] then
        table.insert(hero_priority_data[1], tempOwnerOccupation1[1])
        if tempOwnerOccupation1[2] then
            table.insert(hero_priority_data[2], tempOwnerOccupation1[2])
            for i=3, #tempOwnerOccupation1 do
                table.insert(hero_priority_data[3], tempOwnerOccupation1[i] )
            end
        end
    end
    if tempOwnerOccupation2[1] then
        table.insert(hero_priority_data[1], tempOwnerOccupation2[1])
        if tempOwnerOccupation2[2] then
            table.insert(hero_priority_data[2], tempOwnerOccupation2[2])
            for i=3, #tempOwnerOccupation2 do
                table.insert(hero_priority_data[3], tempOwnerOccupation2[i] )
            end
        end
    end
    if tempOwnerOccupation3[1] then
        table.insert(hero_priority_data[1], tempOwnerOccupation3[1])
        if tempOwnerOccupation3[2] then
            table.insert(hero_priority_data[2], tempOwnerOccupation3[2])
            for i=3, #tempOwnerOccupation3 do
                table.insert(hero_priority_data[3], tempOwnerOccupation3[i] )
            end
        end
    end
    if tempOwnerOccupation4[1] then
        table.insert(hero_priority_data[1], tempOwnerOccupation4[1])
        if tempOwnerOccupation4[2] then
            table.insert(hero_priority_data[2], tempOwnerOccupation4[2])
            for i=3, #tempOwnerOccupation4 do
                table.insert(hero_priority_data[3], tempOwnerOccupation4[i] )
            end
        end
    end
    if tempOwnerOccupation5[1] then
        table.insert(hero_priority_data[1], tempOwnerOccupation5[1])
        if tempOwnerOccupation5[2] then
            table.insert(hero_priority_data[2], tempOwnerOccupation5[2])
            for i=3, #tempOwnerOccupation5 do
                table.insert(hero_priority_data[3], tempOwnerOccupation5[i] )
            end
        end
    end
    if tempOwnerOccupation6[1] then
        table.insert(hero_priority_data[1], tempOwnerOccupation6[1])
        if tempOwnerOccupation6[2] then
            table.insert(hero_priority_data[2], tempOwnerOccupation6[2])
            for i=3, #tempOwnerOccupation6 do
                table.insert(hero_priority_data[3], tempOwnerOccupation6[i] )
            end
        end
    end
 
    table.sort(hero_priority_data[1], this.sortPower)
    table.sort(hero_priority_data[2], this.sortPower)
    table.sort(hero_priority_data[3], this.sortPower)
    return hero_priority_data
end

function UIEquipmentAllocation.sortPower( a, b)
    if a["power"] and b["power"] then
        return a["power"] > b["power"]
    else
        return false
    end
end

function UIEquipmentAllocation.UpdateItemRender( index, obj ) 
    local item_title = obj:GetChild("title") 
    local item_type_controller = obj:GetController("type")
    if index == 0 then
        item_title.text = getLanguage("EquipAllocation2")
        item_type_controller:SetSelectedIndex(0)
    elseif index == 1 then
        item_title.text = getLanguage("EquipAllocation3")
        item_type_controller:SetSelectedIndex(1)
    else 
        item_title.text = getLanguage("EquipAllocation4")
        item_type_controller:SetSelectedIndex(2)
    end

    local pre_count = 0
    local pre_height = this.smart_list_y
    for pre_index=1, index do
        local num = #this.curHeroPriority[pre_index]
        pre_count = pre_count+num
        local row = math.ceil(num/6)
        if row < 1 then
            row = 1
        end
        pre_height = pre_height + 100 +  row * 176
    end
    pre_height = pre_height + index*15
    local sub_item_num = #this.curHeroPriority[index+1] 
    this.sub_item = this.sub_item or {}
    local item_index
    for sub_index = 1, sub_item_num do 
        item_index = pre_count+sub_index
        if this.sub_item[item_index] == nil then
            this.sub_item[item_index] = newGComponent("HeadRectItem","CommonUI")
            this.sub_item[item_index].gameObjectName = "item"
        else
            this.sub_item[item_index].visible = true
        end
        obj:AddChild(this.sub_item[item_index]) 
        this.sub_item[item_index].scaleX = 0.8
        this.sub_item[item_index].scaleY = 0.8 
        this.sub_item[item_index].x = 22 + 156 * math.fmod(sub_index-1, 6)
        this.sub_item[item_index].y = 58 + math.floor((sub_index-1)/6) * 176

        local item_info = this.curHeroPriority[index+1][sub_index]
        this.showItemInfo( this.sub_item[item_index], item_info, index, item_index, pre_height)
    end 
    local row_count = math.ceil(sub_item_num/6)
    if row_count < 1 then
        row_count = 1
    end
    obj.height = 100 +  row_count * 176

end

function UIEquipmentAllocation.ChangeItemInfo(item_info, index, next_index) 
    table.insert(this.curHeroPriority[next_index+1], item_info)
    local list = this.curHeroPriority[index+1] 
    this.curHeroPriority[index+1] = {}
    for _, v in pairs(list) do
        if v and v.partnerId ~= item_info.partnerId then
            table.insert(this.curHeroPriority[index+1], v)
        end
    end
    table.sort(this.curHeroPriority[next_index+1], this.sortPower)
    table.sort(this.curHeroPriority[index+1], this.sortPower) 
    this.SmartHeroList.numItems = 3
end

function UIEquipmentAllocation.showItemInfo( obj, item_info, index, item_index, pre_height)

    local quality = obj:GetChild("quality")
    local qualityBG = obj:GetChild("qualityBG")
    local icon = obj:GetChild("icon") 
    local lv = obj:GetChild("level")
    local lvbg = obj:GetChild("n29")
    local typeIcon = obj:GetChild("Occupation")
    local typeShowController = obj:GetController("Occupation")
    local hasUse = obj:GetController("ctrlHadUsed")
    local hadBattle = obj:GetController("ctrlHadBattle")
    local hadAssist = obj:GetController("ctrlHadAssist")
    local choose = obj:GetChild("maskChoose")
    local unActive = obj:GetChild("unActive")
    local emptyCtrl = obj:GetController("empty")
    local banCtrl = obj:GetController("Ban")
    local circletype = obj:GetController("CircleType")
    local circleCtrl = obj:GetController("Circle")
    local comIcon = obj:GetChild("Com_icon")
    local useCtrl = obj:GetController("UseTime")
    local useTxt = obj:GetChild("Text_UseTime")
    local enemySelectCtrl = obj:GetController("HadSelect")
    local levelShowCtrl = obj:GetController("isShowLevel")--0显示等级以及底框 1不显示
    if quality then
        quality.visible = false
        qualityBG.visible = false
    end
    icon.visible = false
    if item_info then 
        if emptyCtrl then
            emptyCtrl.selectedIndex = 0
        end
        if item_info["star"] ~= nil then
            item_info["quality"] = logicMgr.HeroManager.starToQuality(item_info["star"]);
        end 
        if banCtrl then
            banCtrl.selectedIndex = 0
        end 
        if circleCtrl and circleCtrl.selectedIndex == 1 then
            if circletype then
                if isSeason then
                    circletype.selectedIndex = 1
                else
                    circletype.selectedIndex = 2
                end
            end
        end 
        if useCtrl then
            if logicMgr.HeroManager.NotHaveByModeId(item_info.partnerModelId) then
                local num = logicMgr.RankBattleManager.HeroUsed(item_info.partnerModelId) or 0;
                local max = G.dataTable["t_global"]["221"].f_int_value
                if max - num <= 0 then
                    useCtrl.selectedIndex = 2
                else
                    useCtrl.selectedIndex = 1
                end
                useTxt.text = (max - num).."/"..max
            else
                useCtrl.selectedIndex = 0
            end
        end
        if logicMgr.RankBattleManager.BanPick() and enemySelectCtrl then
            if logicMgr.RankBattleManager.BPCanChooseHeroByModelId(item_info.partnerModelId) then
                enemySelectCtrl.selectedIndex = 1
            else
                enemySelectCtrl.selectedIndex = 0
            end
        end 
        local barController = obj:GetController("Bar")
        if barController ~= nil then
            barController.selectedIndex = 0
        end
        local newController = obj:GetController("new")
        if newController ~= nil then 
            newController.selectedIndex = 0
        end
        local showSSRController = obj:GetController("SSR")
        if showSSRController ~= nil then 
            showSSRController.selectedIndex = 0
        end
        hasUse:SetSelectedIndex(0)
        hadBattle:SetSelectedIndex(0)
        hadAssist:SetSelectedIndex(0)
        choose.visible = false
        unActive.visible = false
 
        if levelShowCtrl ~= nil then
            if item_info["level"] ~= nil and item_info["level"] > 0 then 
                levelShowCtrl.selectedIndex = 0 
                lv.visible = true
                lvbg.visible = true
                local level, lvType = logicMgr.HeroManager.getHeroShowLevelByPartnerId(item_info.partnerId)
                lv.text = string.TextColor(string.format(getLanguage("Level"), level),logicMgr.HeroManager.lvColors[lvType])
            else 
                levelShowCtrl.selectedIndex = 1 
            end
        end
 
        if item_info["star"] ~= nil and item_info["star"] > 0 then 
            local numstar = math.floor(item_info["star"] * 0.0001);
            if numstar > 5 then
                numstar = 5
            end 
        end
        if item_info["icon"] ~= nil then
            local heroId = item_info["partnerModelId"]
            local skinId = nil
            if heroId then
                skinId = logicMgr.SkinManager.getHeroSkinId(heroId)
            end
            if circleCtrl and circleCtrl.selectedIndex == 1 then
                comIcon.visible = true
                comIcon:GetChild("icon").url = "ui://ICONAtlas/" .. item_info.icon
                if skinId then
                    comIcon:GetChild("icon").url = logicMgr.SkinManager.GetHeroIconBySkinId(skinId)
                end
            else
                icon.visible = true
                icon:GetChild("icon").url = "ui://ICONAtlas/" .. item_info.icon
                if skinId then
                    icon:GetChild("icon").url = logicMgr.SkinManager.GetHeroIconBySkinId(skinId)
                end
            end
            icon.visible = true
            icon:GetChild("icon").url = "ui://ICONAtlas/" .. item_info.icon
            if skinId then
                icon:GetChild("icon").url = logicMgr.SkinManager.GetHeroIconBySkinId(skinId)
            end

            if item_info["quality"] == nil or item_info["quality"] == 0 then
                item_info["quality"] = 1
            elseif item_info["quality"] > #Config.IconQuality then
                item_info["quality"] = #Config.IconQuality
            end
            quality.visible = true
            qualityBG.visible = true
            quality.url = "ui://ICONAtlas/" .. Config.IconFrame[item_info["quality"]]
            qualityBG.url = "ui://ICONAtlas/" .. Config.IconQuality[item_info["quality"]] 
        end
        if typeShowController ~= nil then
            if item_info["type"] ~= nil then
                typeShowController.selectedIndex = 0
                typeIcon.url = "ui://ICONAtlas/" .. EnumConst.HeroTypeIcon[item_info["type"]];
            else
                typeShowController.selectedIndex = 1
            end
        end
        
        -- if item_info["state"] ~= nil then 
        --     if ZZMathBit.andOp(item_info["state"], EnumConst.HeroHeadStateEnum.UnActive) > 0 then
        --         unActive.visible = true
        --     else
        --         unActive.visible = false
        --     end
            -- if ZZMathBit.andOp(item_info["state"], EnumConst.HeroHeadStateEnum.DEAD) > 0 then
            --     obj.grayed = true
            -- else
            --     obj.grayed = false
            -- end
        -- else
        --     hadBattle:SetSelectedIndex(0)
        -- end
         
        if item_info["new"] ~= nil and newController ~= nil then
            newController.selectedIndex = 1
        end
        if item_info["showSSR"] and showSSRController ~= nil then
            showSSRController.selectedIndex = 1
        end 
    end
  
    obj.onTouchBegin:Clear()
    obj.onTouchEnd:Clear()
    obj.onTouchBegin:Add(function(evt)
        this.OnTouchStart(evt, item_info)
    end)
    obj.onTouchEnd:Add(function()
        this.OnTouchUp(item_info, obj, item_index, index, pre_height)
    end)
end

function UIEquipmentAllocation.OnTouchStart(evt, item_info) 
    this.timerId = utimer.timeCall(function() 
        showUI(PanelNames.UICharactorInfoHero, item_info, nil, true)
        this.timerId = nil
    end, 500, 1)
end
function UIEquipmentAllocation.OnTouchUp(item_info, obj, item_index, index, pre_height) 
    if this.timerId ~= nil then
        utimer.remove(this.timerId)
        this.timerId = nil
        if this.cur_show_item_index and this.cur_show_item_index == item_index then
            DestoryUI(PanelNames.UIPriorityChange)
            this.cur_show_item_index = nil
        else
            this.cur_show_item_index = item_index
            local data = {}
            data.index = index
            data.item_info = item_info  
            data.x = obj.x-70
            data.y = pre_height + obj.y - 150
            if data.x < 0 then
                data.x = 0
            elseif data.x > 678  then
                data.x = 678
            end
            if data.y > this.smart_list_y + this.smart_list_height then
                data.y = this.smart_list_y + this.smart_list_height
            end
            if isOpenUI(PanelNames.UIPriorityChange) then
                local ui_priority_change = CtrlManager.GetCtrl(PanelNames.UIPriorityChange)
                ui_priority_change.refreshData(data)
            else
                showUI(PanelNames.UIPriorityChange, data)
            end
        end
    end
end

function UIEquipmentAllocation.clearData()
    this.cur_show_item_index = nil
end
 
function UIEquipmentAllocation.addEvent() 
    this.bgClose.onClick:Add(this.OnClickBack)
    this.btnBack.onClick:Add(this.OnClickBack)
    this.btnAllocation.onClick:Add(this.OnClickOneKeyAllocation)
end

function UIEquipmentAllocation.removeEvent() 
    if  this.bgClose ~= nil then
        this.bgClose.onClick:Clear()
        this.btnBack.onClick:Clear()
        this.btnAllocation.onClick:Clear()
    end
end

function UIEquipmentAllocation.GetCurPriorityData()
    local data = {}
    data.priority1 = {}
    if this.curHeroPriority ~= nil and this.curHeroPriority[1] ~= nil then
        for _, v in pairs(this.curHeroPriority[1]) do
            table.insert(data.priority1, v.partnerId)
        end
    end
    data.priority2 = {} 
    if this.curHeroPriority ~= nil and  this.curHeroPriority[2] ~= nil then
        for _, v in pairs(this.curHeroPriority[2]) do
            table.insert(data.priority2, v.partnerId)
        end
    end
    data.priority3 = {} 
    if  this.curHeroPriority ~= nil and this.curHeroPriority[3] ~= nil then
        for _, v in pairs(this.curHeroPriority[3]) do
            table.insert(data.priority3, v.partnerId)
        end
    end
    return data
end


function UIEquipmentAllocation.OnDisable()
    FireEvent(Config.EventType.Close_UIEquipmentAllocation);
end
function UIEquipmentAllocation.OnDestroy() 

    if isOpenUI(PanelNames.UIPriorityChange) then
        closeUI(PanelNames.UIPriorityChange)
    end

    local data = this.GetCurPriorityData()
    if next(data.priority1) ~= nil or next(data.priority2) ~= nil or next(data.priority3) ~= nil then
        equipHandler.sendReqSetSmartWearPriority( data )
    end
    this.hasInit = nil
    this.select_index = nil 
    this.select_sub_index = nil 
    this.removeEvent()
    this.bgClose = nil
    if this.sub_item then
        for k, v in pairs(this.sub_item) do
            v.onClick:Clear()
            v.onTouchBegin:Clear()
            v.onTouchEnd:Clear()
            this.sub_item[k] = nil
        end
        this.sub_item = nil
    end
    equipHandler.refreshHeroList = nil
end

function UIEquipmentAllocation.OnClickBack()
    DestoryUI(PanelNames.UIEquipmentAllocation)
end

function UIEquipmentAllocation.GetBestEquipItem(part_equip_list, hero_type, before_item)
    local best_power_item = nil
    local curHeroType = (hero_type~=nil and hero_type>0) and hero_type or 0
    local tmp_item = nil
    for k, item in pairs(part_equip_list) do   
        if (curHeroType == 0 or item.heroType == curHeroType) then
            if best_power_item then
                if item.power > best_power_item.power then
                    best_power_item = item
                elseif item.power == best_power_item.power and item.partnerId == nil then
                    best_power_item = item
                end
            else
                best_power_item = item
            end
            if before_item and before_item.partnerId ~= nil and item.partnerId ~= nil then 
                if item.itemId == before_item.itemId and  item.partnerId == before_item.partnerId then
                    tmp_item = item
                end
            end
        end 
    end
    if tmp_item ~= nil then 
        if tmp_item.power >= best_power_item.power then 
            best_power_item = tmp_item
        end
    end
    for k, v in pairs(part_equip_list)  do 
        if best_power_item ~= nil and v.itemId == best_power_item.itemId then 
            v.num = tonumber(v.num)
            if  v.num > 1 then
                v.num = v.num-1
            else
                table.remove(part_equip_list, k) 
            end
        end
    end
    return best_power_item
end

function UIEquipmentAllocation.IsNotSameEquip( item1, item2)
    if item1 == nil and item2 == nil then
        return false
    elseif item1 == nil and item2 ~= nil then
        return true
    elseif item1 ~= nil and item2 == nil then
        return true
    else
        return item1.power ~= item2.power
    end

end

function UIEquipmentAllocation.OnClickOneKeyAllocation()
    this.data_result = {}
    this.data_result.hero_data = {}
    local smart_wear_list = {}  
    this.smart_unwear_list = {}  
    local part1_list = logicMgr.EquipManager.getAllEquipsByPart(EnumConst.EquipPartEnum.HAND)
    local part2_list = logicMgr.EquipManager.getAllEquipsByPart(EnumConst.EquipPartEnum.HEAD)
    local part3_list = logicMgr.EquipManager.getAllEquipsByPart(EnumConst.EquipPartEnum.BODY)
    local part4_list = logicMgr.EquipManager.getAllEquipsByPart(EnumConst.EquipPartEnum.LEG)
    local all_hero_equips_key_partnerid = logicMgr.EquipManager.getAllHeroEquipListKeyPartnerId() or {}
    if this.curHeroPriority[1] then
        for _, v in ipairs(this.curHeroPriority[1]) do 
            
            local hero_item = {}
            hero_item.item_info = v 
            local equips = all_hero_equips_key_partnerid[v.partnerId] or {}
            hero_item.before_equip1 = this.GetEquipByPartnerPart(equips, EnumConst.EquipPartEnum.HAND) 
            hero_item.before_equip2 = this.GetEquipByPartnerPart(equips, EnumConst.EquipPartEnum.HEAD)  
            hero_item.before_equip3 = this.GetEquipByPartnerPart(equips, EnumConst.EquipPartEnum.BODY) 
            hero_item.before_equip4 = this.GetEquipByPartnerPart(equips, EnumConst.EquipPartEnum.LEG) 

            local hero_type = v.type
            local part1_item = this.GetBestEquipItem(part1_list, hero_type, hero_item.before_equip1)
            local part2_item = this.GetBestEquipItem(part2_list, hero_type, hero_item.before_equip2)
            local part3_item = this.GetBestEquipItem(part3_list, hero_type, hero_item.before_equip3)
            local part4_item = this.GetBestEquipItem(part4_list, hero_type, hero_item.before_equip4) 

            hero_item.after_equip1 = part1_item
            hero_item.after_equip2 = part2_item
            hero_item.after_equip3 = part3_item
            hero_item.after_equip4 = part4_item
            local ret1 = this.IsNotSameEquip( hero_item.before_equip1, hero_item.after_equip1)
            local ret2 = this.IsNotSameEquip( hero_item.before_equip2, hero_item.after_equip2)
            local ret3 = this.IsNotSameEquip( hero_item.before_equip3, hero_item.after_equip3)
            local ret4 = this.IsNotSameEquip( hero_item.before_equip4, hero_item.after_equip4)
            if ret1 or ret2 or ret3 or ret4 then
                this.AddUnWearItem(hero_item.before_equip1, part1_item, v.partnerId)
                this.AddUnWearItem(hero_item.before_equip2, part2_item, v.partnerId)
                this.AddUnWearItem(hero_item.before_equip3, part3_item, v.partnerId)
                this.AddUnWearItem(hero_item.before_equip4, part4_item, v.partnerId) 
                local wear_item = this.GetWearItem( v.partnerId,  part1_item, part2_item,  part3_item, part4_item)  
                table.insert(smart_wear_list, wear_item) 
                table.insert(this.data_result.hero_data, hero_item)
            end 
        end
    end
    if this.curHeroPriority[2] then
        for _, v in ipairs(this.curHeroPriority[2]) do
            
            local hero_item = {}  
            hero_item.item_info = v 
            local equips = all_hero_equips_key_partnerid[v.partnerId] or {}
            hero_item.before_equip1 = this.GetEquipByPartnerPart(equips, EnumConst.EquipPartEnum.HAND) 
            hero_item.before_equip2 = this.GetEquipByPartnerPart(equips, EnumConst.EquipPartEnum.HEAD)  
            hero_item.before_equip3 = this.GetEquipByPartnerPart(equips, EnumConst.EquipPartEnum.BODY) 
            hero_item.before_equip4 = this.GetEquipByPartnerPart(equips, EnumConst.EquipPartEnum.LEG) 

            local hero_type = v.type
            local part1_item = this.GetBestEquipItem(part1_list, hero_type, hero_item.before_equip1)
            local part2_item = this.GetBestEquipItem(part2_list, hero_type, hero_item.before_equip2)
            local part3_item = this.GetBestEquipItem(part3_list, hero_type, hero_item.before_equip3)
            local part4_item = this.GetBestEquipItem(part4_list, hero_type, hero_item.before_equip4)  

            hero_item.after_equip1 = part1_item
            hero_item.after_equip2 = part2_item
            hero_item.after_equip3 = part3_item
            hero_item.after_equip4 = part4_item
            local ret1 = this.IsNotSameEquip( hero_item.before_equip1, hero_item.after_equip1)
            local ret2 = this.IsNotSameEquip( hero_item.before_equip2, hero_item.after_equip2)
            local ret3 = this.IsNotSameEquip( hero_item.before_equip3, hero_item.after_equip3)
            local ret4 = this.IsNotSameEquip( hero_item.before_equip4, hero_item.after_equip4)
            if ret1 or ret2 or ret3 or ret4 then
                this.AddUnWearItem(hero_item.before_equip1, part1_item, v.partnerId)
                this.AddUnWearItem(hero_item.before_equip2, part2_item, v.partnerId)
                this.AddUnWearItem(hero_item.before_equip3, part3_item, v.partnerId)
                this.AddUnWearItem(hero_item.before_equip4, part4_item, v.partnerId)
                local wear_item = this.GetWearItem( v.partnerId,  part1_item, part2_item,part3_item, part4_item)  
                table.insert(smart_wear_list, wear_item)
                table.insert(this.data_result.hero_data, hero_item)
            end 
        end
    end
    if this.curHeroPriority[3] then
        for _, v in ipairs(this.curHeroPriority[3]) do
            
            local hero_item = {}
            hero_item.item_info = v  
            local equips = all_hero_equips_key_partnerid[v.partnerId] or {}
            hero_item.before_equip1 = this.GetEquipByPartnerPart(equips, EnumConst.EquipPartEnum.HAND) 
            hero_item.before_equip2 = this.GetEquipByPartnerPart(equips, EnumConst.EquipPartEnum.HEAD)  
            hero_item.before_equip3 = this.GetEquipByPartnerPart(equips, EnumConst.EquipPartEnum.BODY) 
            hero_item.before_equip4 = this.GetEquipByPartnerPart(equips, EnumConst.EquipPartEnum.LEG) 

            local hero_type = v.type
            local part1_item = this.GetBestEquipItem(part1_list, hero_type, hero_item.before_equip1)
            local part2_item = this.GetBestEquipItem(part2_list, hero_type, hero_item.before_equip2)
            local part3_item = this.GetBestEquipItem(part3_list, hero_type, hero_item.before_equip3)
            local part4_item = this.GetBestEquipItem(part4_list, hero_type, hero_item.before_equip4)  

            hero_item.after_equip1 = part1_item
            hero_item.after_equip2 = part2_item 
            hero_item.after_equip3 = part3_item
            hero_item.after_equip4 = part4_item
            local ret1 = this.IsNotSameEquip( hero_item.before_equip1, hero_item.after_equip1)
            local ret2 = this.IsNotSameEquip( hero_item.before_equip2, hero_item.after_equip2)
            local ret3 = this.IsNotSameEquip( hero_item.before_equip3, hero_item.after_equip3)
            local ret4 = this.IsNotSameEquip( hero_item.before_equip4, hero_item.after_equip4)
            if ret1 or ret2 or ret3 or ret4 then
                this.AddUnWearItem(hero_item.before_equip1, part1_item, v.partnerId)
                this.AddUnWearItem(hero_item.before_equip2, part2_item, v.partnerId)
                this.AddUnWearItem(hero_item.before_equip3, part3_item, v.partnerId)
                this.AddUnWearItem(hero_item.before_equip4, part4_item, v.partnerId)
                local wear_item = this.GetWearItem( v.partnerId,  part1_item, part2_item, part3_item, part4_item)  
                table.insert(smart_wear_list, wear_item)
                table.insert(this.data_result.hero_data, hero_item)
            end 
        end
    end  
    if #this.data_result.hero_data > 0 then 
         equipHandler.sendSmartWearEquip( smart_wear_list, this.smart_unwear_list, this.GetCurPriorityData() ) 
    else
        UISysTips.AddMsg(getLanguage("EquipAllocation8"))
    end
    
end

function UIEquipmentAllocation.GetEquipByPartnerPart(equips, part)
    if equips then
        for _, v in pairs(equips) do
            if v and v.part == part then
                return v
            end
        end
    end
end

function UIEquipmentAllocation.AddUnWearItem(equip_item, equip_item1, partnerId)
    if (equip_item and equip_item.partnerId ~= nil) and (equip_item1 and equip_item1.partnerId ~= nil) then
        if  partnerId and equip_item.partnerId == equip_item1.partnerId and equip_item.partnerId == partnerId then
            return
        end
    end

    if equip_item and equip_item.partnerId ~= nil then   
        this.smart_unwear_list[equip_item.partnerId] = this.smart_unwear_list[equip_item.partnerId] or {}
        if this.smart_unwear_list[equip_item.partnerId].partnerId == nil then
            this.smart_unwear_list[equip_item.partnerId].partnerId = equip_item.partnerId 
        end
        if this.smart_unwear_list[equip_item.partnerId].index1 == nil then
            this.smart_unwear_list[equip_item.partnerId].index1 = tonumber(equip_item.part) 
        elseif this.smart_unwear_list[equip_item.partnerId].index2 == nil then
            this.smart_unwear_list[equip_item.partnerId].index2 = tonumber(equip_item.part)
        elseif this.smart_unwear_list[equip_item.partnerId].index3 == nil then
            this.smart_unwear_list[equip_item.partnerId].index3 = tonumber(equip_item.part)
        elseif this.smart_unwear_list[equip_item.partnerId].index4 == nil then
            this.smart_unwear_list[equip_item.partnerId].index4 = tonumber(equip_item.part)
        end
    end

    if equip_item1 and equip_item1.partnerId ~= nil then   
        this.smart_unwear_list[equip_item1.partnerId] = this.smart_unwear_list[equip_item1.partnerId] or {}
        if this.smart_unwear_list[equip_item1.partnerId].partnerId == nil then
            this.smart_unwear_list[equip_item1.partnerId].partnerId = equip_item1.partnerId 
        end
        if this.smart_unwear_list[equip_item1.partnerId].index1 == nil then
            this.smart_unwear_list[equip_item1.partnerId].index1 = tonumber(equip_item1.part) 
        elseif this.smart_unwear_list[equip_item1.partnerId].index2 == nil then
            this.smart_unwear_list[equip_item1.partnerId].index2 = tonumber(equip_item1.part)
        elseif this.smart_unwear_list[equip_item1.partnerId].index3 == nil then
            this.smart_unwear_list[equip_item1.partnerId].index3 = tonumber(equip_item1.part)
        elseif this.smart_unwear_list[equip_item1.partnerId].index4 == nil then
            this.smart_unwear_list[equip_item1.partnerId].index4 = tonumber(equip_item1.part)
        end
    end
end

function UIEquipmentAllocation.GetWearItem( partnerId,  equip_item1, equip_item2, equip_item3, equip_item4)  
    local wear_item = {}
    wear_item.partnerId = partnerId
    if equip_item1 then
        wear_item.itemId1 = equip_item1.itemId 
    else
        wear_item.itemId1 = 0
    end
    if equip_item2 then
        wear_item.itemId2 = equip_item2.itemId
    else
        wear_item.itemId2 = 0
    end
    if equip_item3 then
        wear_item.itemId3 = equip_item3.itemId
    else
        wear_item.itemId3 = 0
    end
    if equip_item4 then
        wear_item.itemId4 = equip_item4.itemId
    else
        wear_item.itemId4 = 0
    end
    return wear_item
end

function UIEquipmentAllocation.ResSmartWear()
    if this.data_result and this.data_result.hero_data and #this.data_result.hero_data > 0 then 
        if isOpenUI(PanelNames.UIAllocationResult) then
            local ui_allocation_result = CtrlManager.GetCtrl(PanelNames.UIAllocationResult)
            ui_allocation_result.UpdateResultData( this.data_result )
        else
            showUI(PanelNames.UIAllocationResult, this.data_result)
        end

    end
end


-- 更新优先级数据
function UIEquipmentAllocation.UpdatePriorityData( msg ) 

    if msg  then
        if (msg.priority1 and next(msg.priority1) ~= nil) or (msg.priority2 and next(msg.priority2) ~= nil)  or (msg.priority3 and next(msg.priority3) ~= nil)  then
            this.curHeroPriority = {}
            this.curHeroPriority[1] = {}
            this.curHeroPriority[2] = {}
            this.curHeroPriority[3] = {}
            local all_list = logicMgr.HeroManager.getOwnerHeroListLevelUp(nil, nil, 1) or {}
            local all_hero = {}
            for _, v in pairs(all_list) do
                if v then
                    all_hero[tostring(v.partnerId)] = v
                end
            end
            local key
            for _, v in pairs(msg.priority1) do
                key = tostring(v)
                if all_hero[key] then 
                    table.insert(this.curHeroPriority[1], all_hero[key])
                    all_hero[key] = nil
                end
            end
            for _, v in pairs(msg.priority2) do
                key = tostring(v)
                if all_hero[key] then
                    table.insert(this.curHeroPriority[2], all_hero[key])
                    all_hero[key] = nil
                end
            end
            for _, v in pairs(msg.priority3) do
                key = tostring(v)
                if all_hero[key] then
                    table.insert(this.curHeroPriority[3], all_hero[key])
                    all_hero[key] = nil
                end
            end
            if all_hero then
                for _, v in pairs(all_hero) do
                    if v then
                        table.insert(this.curHeroPriority[3], v)
                    end
                end
            end
            all_hero = nil
            table.sort(this.curHeroPriority[1], this.sortPower)
            table.sort(this.curHeroPriority[2], this.sortPower)
            table.sort(this.curHeroPriority[3], this.sortPower)
        else
            this.curHeroPriority = this.GetCurHeroPriority()
        end
    else
        this.curHeroPriority = this.GetCurHeroPriority()  
    end
    if this.SmartHeroList ~= nil then
        this.SmartHeroList.numItems = 3
    end
end

return UIEquipmentAllocation